/**
 * 微交互组件
 * 提供统一的微交互反馈效果
 */
const AnimationUtils = require('../../utils/animations');

Component({
  properties: {
    // 交互类型
    type: {
      type: String,
      value: 'tap' // tap, longpress, swipe, drag
    },
    
    // 反馈类型
    feedback: {
      type: String,
      value: 'scale' // scale, bounce, pulse, shake, glow, ripple
    },
    
    // 主题
    theme: {
      type: String,
      value: 'default' // default, his, hers
    },
    
    // 是否禁用
    disabled: {
      type: Boolean,
      value: false
    },
    
    // 触发延迟
    delay: {
      type: Number,
      value: 0
    },
    
    // 自定义样式类
    customClass: {
      type: String,
      value: ''
    },
    
    // 是否显示波纹效果
    ripple: {
      type: Boolean,
      value: false
    },
    
    // 触觉反馈
    haptic: {
      type: Boolean,
      value: true
    }
  },
  
  data: {
    animationData: {},
    rippleAnimation: {},
    isAnimating: false,
    rippleVisible: false
  },
  
  lifetimes: {
    attached() {
      this.initComponent();
    }
  },
  
  methods: {
    /**
     * 初始化组件
     */
    initComponent() {
      // 初始化动画状态
      this.setData({
        animationData: {},
        rippleAnimation: {},
        isAnimating: false,
        rippleVisible: false
      });
    },
    
    /**
     * 处理点击事件
     */
    onTap(e) {
      if (this.data.disabled || this.data.isAnimating) return;
      
      this.triggerInteraction('tap', e);
      this.triggerEvent('tap', e.detail);
    },
    
    /**
     * 处理长按事件
     */
    onLongPress(e) {
      if (this.data.disabled) return;
      
      this.triggerInteraction('longpress', e);
      this.triggerEvent('longpress', e.detail);
    },
    
    /**
     * 处理触摸开始
     */
    onTouchStart(e) {
      if (this.data.disabled) return;
      
      this.touchStartTime = Date.now();
      this.touchStartPos = {
        x: e.touches[0].clientX,
        y: e.touches[0].clientY
      };
      
      // 显示按下状态
      this.showPressState();
      
      this.triggerEvent('touchstart', e.detail);
    },
    
    /**
     * 处理触摸移动
     */
    onTouchMove(e) {
      if (this.data.disabled || !this.touchStartPos) return;
      
      const currentPos = {
        x: e.touches[0].clientX,
        y: e.touches[0].clientY
      };
      
      const deltaX = currentPos.x - this.touchStartPos.x;
      const deltaY = currentPos.y - this.touchStartPos.y;
      const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
      
      // 如果移动距离超过阈值，取消按下状态
      if (distance > 10) {
        this.hidePressState();
      }
      
      this.triggerEvent('touchmove', {
        ...e.detail,
        deltaX,
        deltaY,
        distance
      });
    },
    
    /**
     * 处理触摸结束
     */
    onTouchEnd(e) {
      if (this.data.disabled) return;
      
      this.hidePressState();
      
      const touchEndTime = Date.now();
      const touchDuration = touchEndTime - (this.touchStartTime || 0);
      
      this.triggerEvent('touchend', {
        ...e.detail,
        duration: touchDuration
      });
      
      // 清理触摸状态
      this.touchStartTime = null;
      this.touchStartPos = null;
    },
    
    /**
     * 触发交互效果
     */
    triggerInteraction(type, e) {
      if (this.data.disabled) return;
      
      // 触觉反馈
      if (this.data.haptic) {
        this.triggerHapticFeedback(type);
      }
      
      // 延迟执行动画
      setTimeout(() => {
        this.playFeedbackAnimation(type, e);
        
        // 波纹效果
        if (this.data.ripple && type === 'tap') {
          this.playRippleEffect(e);
        }
      }, this.data.delay);
    },
    
    /**
     * 播放反馈动画
     */
    playFeedbackAnimation(type, e) {
      this.setData({ isAnimating: true });
      
      let animation;
      
      switch (this.data.feedback) {
        case 'scale':
          animation = AnimationUtils.buttonClick('scale');
          break;
        case 'bounce':
          animation = AnimationUtils.buttonClick('bounce');
          break;
        case 'pulse':
          animation = AnimationUtils.buttonClick('pulse');
          break;
        case 'shake':
          animation = AnimationUtils.buttonClick('shake');
          break;
        case 'glow':
          animation = AnimationUtils.buttonClick('glow');
          break;
        case 'heartbeat':
          animation = AnimationUtils.heartbeat('love');
          break;
        case 'breathing':
          animation = AnimationUtils.breathing(0.5);
          break;
        default:
          animation = AnimationUtils.buttonClick('scale');
      }
      
      this.setData({
        animationData: animation.export()
      });
      
      // 动画结束后重置状态
      setTimeout(() => {
        this.setData({ isAnimating: false });
      }, AnimationUtils.config.duration.normal);
    },
    
    /**
     * 播放波纹效果
     */
    playRippleEffect(e) {
      if (!this.data.ripple) return;
      
      this.setData({ rippleVisible: true });
      
      const rippleAnimation = AnimationUtils.ripple(this.data.theme);
      
      this.setData({
        rippleAnimation: rippleAnimation.export()
      });
      
      // 波纹动画结束后隐藏
      setTimeout(() => {
        this.setData({ rippleVisible: false });
      }, AnimationUtils.config.duration.extra);
    },
    
    /**
     * 显示按下状态
     */
    showPressState() {
      const pressAnimation = AnimationUtils.create({
        duration: AnimationUtils.config.duration.fast
      }).scale(0.98).step();
      
      this.setData({
        animationData: pressAnimation.export()
      });
    },
    
    /**
     * 隐藏按下状态
     */
    hidePressState() {
      const releaseAnimation = AnimationUtils.create({
        duration: AnimationUtils.config.duration.fast
      }).scale(1).step();
      
      this.setData({
        animationData: releaseAnimation.export()
      });
    },
    
    /**
     * 触发触觉反馈
     */
    triggerHapticFeedback(type) {
      try {
        switch (type) {
          case 'tap':
            wx.vibrateShort({ type: 'light' });
            break;
          case 'longpress':
            wx.vibrateShort({ type: 'medium' });
            break;
          case 'success':
            wx.vibrateShort({ type: 'heavy' });
            break;
          case 'error':
            wx.vibrateShort({ type: 'heavy' });
            setTimeout(() => {
              wx.vibrateShort({ type: 'light' });
            }, 100);
            break;
          default:
            wx.vibrateShort({ type: 'light' });
        }
      } catch (error) {
        console.warn('触觉反馈不支持:', error);
      }
    },
    
    /**
     * 播放成功反馈
     */
    playSuccessFeedback() {
      if (this.data.disabled) return;
      
      this.triggerHapticFeedback('success');
      
      const animation = AnimationUtils.successFeedback();
      this.setData({
        animationData: animation.export()
      });
    },
    
    /**
     * 播放错误反馈
     */
    playErrorFeedback() {
      if (this.data.disabled) return;
      
      this.triggerHapticFeedback('error');
      
      const animation = AnimationUtils.errorFeedback();
      this.setData({
        animationData: animation.export()
      });
    },
    
    /**
     * 播放自定义动画
     */
    playCustomAnimation(animationType, options = {}) {
      if (this.data.disabled) return;
      
      let animation;
      
      switch (animationType) {
        case 'heartbeat':
          animation = AnimationUtils.heartbeat(options.emotion || 'love');
          break;
        case 'breathing':
          animation = AnimationUtils.breathing(options.intensity || 0.5);
          break;
        case 'loading':
          animation = AnimationUtils.loading(options.type || 'spin');
          break;
        default:
          animation = AnimationUtils.buttonClick(animationType);
      }
      
      this.setData({
        animationData: animation.export()
      });
    },
    
    /**
     * 重置动画状态
     */
    resetAnimation() {
      this.setData({
        animationData: {},
        rippleAnimation: {},
        isAnimating: false,
        rippleVisible: false
      });
    }
  }
});